<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<c:set var="context"
	value="${pageContext.request.servletContext.contextPath}" />
<script
	src="<spring:url value="/resources/countdown/jquery.tinytimer.js"/>"></script>

<script type="text/javascript">

	var questionNumber = 0;

	//Get question
	var truefalseQuestion = "<div class=\"question\" id=\"edit\"><div class=\"question_number\"><ul><li><h6 class=\"questionId hidden\">"
		+ "</h6><h5 class=\"questionNum\">Question 2:</h5></li></ul></div><div class=\"question_name\"></div><div class=\"question_answer\">"
		+ "<div class=\"vcenter\"><input type=\"radio\" value=\"A\" id=\"A\" name=\"q\"><label for=\"A\">A. True</label></div><div class=\"vcenter\"><input type=\"radio\" id=\"B\" value=\"B\" name=\"q\"><label for=\"B\">B. False</label></div></div></div>";
	// Mutil Choice
	var multiChoiceQuestion = "<div class=\"question\" id=\"edit\"><div class=\"question_number\"><ul><li><h6 class=\"questionId hidden\"></h6>"
		+ "<h5 class=\"questionNum\">Question 1:</h5></li></ul></div><div class=\"question_name\"></div><div class=\"question_answer\">"
		+ "<div class=\"vcenter\"><input type=\"checkbox\" value=\"A\" id=\"A\" name=\"q\"><label for=\"A\"></label></div><div class=\"vcenter\"><input type=\"checkbox\" value=\"B\" id=\"B\" name=\"q\"><label for=\"B\"></label></div><div class=\"vcenter\">"
		+ "<input type=\"checkbox\" value=\"C\" id=\"C\" name=\"q\"><label for=\"C\"></label></div><div class=\"vcenter\"><input type=\"checkbox\" value=\"D\" id=\"D\" name=\"q\"><label for=\"D\"></label></div></div></div>";

	var singleChoiceQuestion = "<div class=\"question\" id=\"edit\"><div class=\"question_number\"><ul><li><h6 class=\"questionId hidden\"></h6>"
		+ "<h5 class=\"questionNum\">Question 1:</h5></li></ul></div><div class=\"question_name\"></div><div class=\"question_answer\">"
		+ "<div class=\"vcenter\"><input type=\"radio\" value=\"A\" id=\"A\" name=\"q\"><label for=\"A\"></label></div><div class=\"vcenter\"><input type=\"radio\" value=\"B\" id=\"B\" name=\"q\"><label for=\"B\"></label></div><div class=\"vcenter\">"
		+ "<input type=\"radio\" value=\"C\" id=\"C\" name=\"q\"><label for=\"C\"></label></div><div class=\"vcenter\"><input type=\"radio\" value=\"D\" id=\"D\" name=\"q\"><label for=\"D\"></label></div></div></div>";

	function showQuestion(type, data) {
			var question = $("#edit");
			var answer = data.answer.split(";");
			if (type == 1) {
				// True/False
				question = $(truefalseQuestion).replaceAll("#edit");
				question.find(".questionId").text(data.questionId);
				question.find(".question_name").text(data.question);
				return false;
			} else if (type == 2) {
				// Single Choice
				question = $(singleChoiceQuestion).replaceAll("#edit");
				question.find("input[value=A]").siblings().text(answer[0].substring(2, answer[0].length));
				question.find("input[value=B]").siblings().text(answer[1].substring(2, answer[1].length));
				question.find("input[value=C]").siblings().text(answer[2].substring(2, answer[2].length));
				question.find("input[value=D]").siblings().text(answer[3].substring(2, answer[3].length));
			} else {
				// Multi Choice
				question = $(multiChoiceQuestion).replaceAll("#edit");
				question.find("input[value=A]").siblings().text(answer[0].substring(2, answer[0].length));
				question.find("input[value=B]").siblings().text(answer[1].substring(2, answer[1].length));
				question.find("input[value=C]").siblings().text(answer[2].substring(2, answer[2].length));
				question.find("input[value=D]").siblings().text(answer[3].substring(2, answer[3].length));
			}
			question.find(".questionId").text(data.questionId);
			question.find(".question_name").text(data.question);
			return false;
		};
		
		$(document).ready(function() {
			var flag = false;
			//In seconds
			var seconds = $("#testDuration").text();
			var minutes = seconds / 60;
			seconds = seconds % 60;
			var m = moment().add('minutes', minutes);
			$('#timer').tinyTimer({
				to : m.toDate(),
				onEnd: function(){
					submitTest();
				},
				onTick: function(){
					if(flag == false){
						//Check remaining time
						var ms = moment(m,"DD/MM/YYYY HH:mm:ss").diff(moment(),"DD/MM/YYYY HH:mm:ss");
						var d = moment.duration(ms);
						//var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
						if(d.asMinutes() < 5){
							$('#timer').addClass("timeout");
							flag = true;
						}
					}
				}
			});
			
			createDialogConfirm();
			createDialogInfo();
			firstCall();
		});
		var type = 1;
		
		$(document).on("click", "#next", function(){
			questionNumber++;
			var testId = $("#testId").text();
			var questionId = $(".questionId").text();
			var answer = "";
			if (type == 3) {// Checkbox
				var rightAnswers = $("#edit .question_answer input[name=q]:checked");
				rightAnswers.each(function() {
					answer += $(this).val();
				});
			} else {// Radio
				answer = $("#edit .question_answer input[name=q]:checked").val();
				if(answer == undefined){
					answer = "";
				}
			}
			//alert(answer);
			//Get answer;
			var requestData = {
					testId : testId,
					questionId : questionId,
					answer : answer,
					questionNumber: questionNumber
				};
			
			$.ajax({
				url : 'next',
				data : JSON.stringify(requestData),
				dataType : 'json',
				contentType : 'application/json; charset=utf-8',
				type : "POST",
				error : function(error) {
					alert("Error End of test!");
					
					return false;
				},
				success : function(data) {
					// Process after add?
					if(data.questionId == null){
						$("#edit").remove();
						$("#control").remove();
						$("#notify").text("Press OK to submit your test!");
						$("#dialog-confirm").dialog("open");
						return false;
					}
					else if(data.questionId == "0000"){
						$("#info").text("Out of time! You can't take this test!");
						$("#dialog-info").dialog("open");
						return false;
					}
					type = data.type;
					try{
						showQuestion(type, data);
						var numberQuestion = $("#numberQuestion").text();
						$(".questionNum").text("Question " + (questionNumber + 1) +"/"+ numberQuestion + ":");
					}catch(e){
						alert(e);
					}
				},
				async : true,
				processData : false
			});
			return false;
		});
		
		$(document).on("click", "#submit", function(){
			$("#dialog-confirm").dialog("open");
			return false;
		});
		
		function firstCall(){
			
			//Get curent question
			questionNumber = parseInt($("#questionNumber").text());
			var testId = $("#testId").text();
			var requestData = {
					testId : testId,
					questionId : "",
					answer : "",
					questionNumber: questionNumber
				};
			$.ajax({
				url : 'next',
				data : JSON.stringify(requestData),
				dataType : 'json',
				contentType : 'application/json; charset=utf-8',
				type : "POST",
				error : function(error) {
					alert("Error " + error);
				},
				success : function(data) {
					// Process after add?
					var type = data.type;
					try{
						showQuestion(type, data);
						var numberQuestion = $("#numberQuestion").text();
						$(".questionNum").text("Question " + (questionNumber + 1) +"/"+ numberQuestion + ":");
					}catch(e){
						alert(e);
					}
				},
				async : true,
				processData : false
			});
			return false;
		};
		
		function submitTest(){
			var id = $("#testId").text();
			$.ajax({
				url : 'point',
				data : id,
				dataType : 'text',
				contentType: 'application/json',
				mimeType: 'application/json',
				type : "POST",
				error : function(error) {

					$("#info").text("Something went wrong!");
					$("#dialog-info").dialog("open");
					return false;
				},
				success : function(data) {

					if(data == "ERROR"){
						$("#info").text("Out of time! Your submission isn't accepted!");
						$("#dialog-info").dialog("open");
					}else{

						$("#info").text("Your mark: " + data +" points. You will be redirected to Submitted Page!");
						$("#dialog-info").dialog("open");
					}

					return false;
				},
				async : true,
				processData : false
			});
		};
		
		function createDialogConfirm() {
			$("#dialog-confirm").dialog({
				autoOpen : false,
				resizable : false,
				modal : true,
				buttons : {
					OK : function() {
						submitTest();
						$(this).dialog("close");
					},
					Cancel: function(){
						$(this).dialog("close");
					}
				}
			});
		};
		
		function createDialogInfo() {
			$("#dialog-info").dialog({
				autoOpen : false,
				resizable : false,
				modal : true,
				buttons : {
					OK : function() {
						$(this).dialog("close");
						window.location.href= "submitted";
					}
				}
			});
		};
</script>
<style>


#timer {
	font-size: 48px;
	float: right;
	color: #014464;
}

.questionNum{
	font-size: xx-large;
}

.question_name{
	font-size: x-large;
}

.question_answer{
	font-size: x-large;
}

.question_answer div label{
	font-weight: normal;
}

input[type='radio'], input[type='checkbox'] {
    transform: scale(1.5);
    vertical-align:top !important;
}

.vcenter {
    line-height: 19px;
    margin: 10px 0px;
}

.error{
	font-size: x-large;
}

.timeout{
	color: red!important;
}
</style>

<div id="dialog-info" title="Submit Info">
	<p>
		<span class="ui-icon ui-icon-alert"
			style="float: left; margin: 0 7px 20px 0;"></span><span id="info"></span>
	</p>
</div>

<div id="dialog-confirm" title="Submit Confirm">
	<p>
		<span class="ui-icon ui-icon-alert"
			style="float: left; margin: 0 7px 20px 0;"></span>Do you want to
		Submit?
	</p>
</div>
<!-- Template for all sub-pages -->
<div id="portal_main_content" align="left">
	<!-- Don't change this -->
	<div id="site_title">

		<!-- ************** -->
		<!-- Able to change -->
		<h2>Test Name: ${submitted.testAndQuizz_student.testAndQuizz.testAndQuizzName}</h2>
		<span id="timer" class="pull-right"></span>
	</div>
	<!-- Don't change this -->
	<div id="site_content">
		<div id="btn_control">

			<!-- ************** -->
			<!-- Able to change -->
			<a href="" class="btn btn-primary" id="submit">Submit</a><h5 id="notify" class="error"></h5>
		</div>
		<div id="table">

			<!-- ************** -->
			<!-- Able to change -->
			<h6 class="hidden" id="testId">${submitted.submittedTestAndQuizzId}</h6>
			<h6 class="hidden" id="testDuration">${duration}</h6>
			<h6 class="hidden" id="numberQuestion">${numberQuestion}</h6>
			<h6 class="hidden" id="questionNumber">${questionNumber}</h6>
			<div id="test">
				<div class="question_part">
					<div class="part_name hidden">
							<ul>
								<li><h6 class="partId hidden">
										<c:out value="122"></c:out>
									</h6>
									<h3 class="partNum">Part:</h3>
									<h3 class="partName">Part Name</h3>
							</ul>
					</div>
					<div class="part_content">
						<div id="edit"></div>
					</div>
				</div>
				<div id="control">
					<a href="" class="btn btn-primary" id="next">Next Question</a>
				</div>
			</div>
		</div>

	</div>
</div>